#!/usr/bin/env python3
"""
工时报告AI服务使用示例
"""

import os
from datetime import datetime
from services.report_service import WorkHoursReportService, ReportConfig, get_report_service
from utils.config import settings


def main():
    """主函数示例"""
    print("🐂 牛马工时报告AI服务使用示例")
    print("=" * 50)
    
    # 1. 初始化服务
    try:
        service = WorkHoursReportService()
        
        print("✅ AI服务初始化成功")
        print(f"🔧 使用配置: {settings.DEEPSEEK_MODEL}")
        print(f"🌐 API地址: {service.base_url}")
        
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        print("💡 提示: 请确保已设置DEEPSEEK_API_KEY环境变量")
        return
    
    # 2. 示例查询
    examples = [
        {
            "query": "BAI HAO在2025年3月的工时记录",
            "description": "按员工和时间查询"
        },
        {
            "query": "显示'AGI部'所有员工的工时统计",
            "description": "按部门查询"
        },
        {
            "query": "查看项目1-PLP-029-A的工时投入情况",
            "description": "按项目查询"
        },
        {
            "query": "统计所有员工本月工作内容",
            "description": "总体统计"
        }
    ]
    
    print("\n📝 示例查询：")
    for i, example in enumerate(examples, 1):
        print(f"{i}. {example['description']}: {example['query']}")
    
    # 3. 演示功能
    try:
        # 选择第一个示例进行演示
        demo_query = examples[0]["query"]
        print(f"\n🔍 演示查询: {demo_query}")
        
        # 3.1 生成SQL
        print("\n步骤1: 生成SQL...")
        sql_result = service.generate_sql_from_query(demo_query)
        print(f"生成的SQL: {sql_result}")
        
        # 3.2 执行查询
        print("\n步骤2: 执行查询...")
        query_result = service.execute_query_with_ai(demo_query)
        if query_result["success"]:
            print(f"查询成功，返回 {len(query_result['data'])} 条记录")
        else:
            print(f"查询失败: {query_result['message']}")
            return
        
        # 3.3 生成Markdown报告
        print("\n步骤3: 生成Markdown报告...")
        config = ReportConfig(report_type="markdown")
        report_result = service.generate_report(query_result["data"], config)
        
        if report_result["success"]:
            print("📄 Markdown报告生成成功:")
            print("-" * 50)
            print(report_result["content"])
            print("-" * 50)
        else:
            print(f"报告生成失败: {report_result['message']}")
        
        # 3.4 生成HTML报告
        print("\n步骤4: 生成HTML报告...")
        config = ReportConfig(report_type="html")
        html_report = service.generate_report(query_result["data"], config)
        
        if html_report["success"]:
            print("📄 HTML报告生成成功")
            # 保存到文件
            output_file = f"output/report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
            os.makedirs(os.path.dirname(output_file), exist_ok=True)
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(html_report["content"])
            print(f"HTML报告已保存到: {output_file}")
        
        # 3.5 生成综合报告
        print("\n步骤5: 生成综合报告...")
        comprehensive_result = service.generate_comprehensive_report(
            demo_query,
            ReportConfig(report_type="markdown")
        )
        
        if comprehensive_result["success"]:
            print("📊 综合报告生成成功")
            print(f"使用的SQL: {comprehensive_result['sql']}")
            print(f"统计信息: {comprehensive_result['statistics']}")
            
            # 保存Markdown报告
            output_file = f"output/comprehensive_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(comprehensive_result["report"])
            print(f"综合报告已保存到: {output_file}")
        
    except Exception as e:
        print(f"❌ 演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
    

def interactive_demo():
    """交互式演示"""
    print("🤖 交互式AI报告生成器")
    print("=" * 50)
    
    try:
        service = get_report_service()
        print("✅ 服务已启动")
        
        while True:
            print("\n选择操作:")
            print("1. 自然语言查询")
            print("2. 生成报告")
            print("3. 综合查询+报告")
            print("4. 退出")
            
            choice = input("\n请输入选择 (1-4): ").strip()
            
            if choice == "1":
                query = input("请输入查询问题: ").strip()
                if query:
                    result = service.execute_query_with_ai(query)
                    print(f"\n查询结果: {result}")
            
            elif choice == "2":
                print("请先执行查询获取数据，然后生成报告")
            
            elif choice == "3":
                query = input("请输入查询问题: ").strip()
                report_type = input("选择报告类型 (html/markdown, 默认markdown): ").strip() or "markdown"
                
                if query:
                    config = ReportConfig(report_type=report_type)
                    result = service.generate_comprehensive_report(query, config)
                    
                    if result["success"]:
                        print(f"\n✅ 报告生成成功!")
                        print(f"报告类型: {result['report_type']}")
                        print(f"统计信息: {result['statistics']}")
                        
                        # 保存报告
                        file_ext = "html" if report_type == "html" else "md"
                        output_file = f"output/interactive_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{file_ext}"
                        os.makedirs(os.path.dirname(output_file), exist_ok=True)
                        with open(output_file, 'w', encoding='utf-8') as f:
                            f.write(result["report"])
                        print(f"报告已保存到: {output_file}")
                    else:
                        print(f"❌ 报告生成失败: {result['message']}")
            
            elif choice == "4":
                break
            
            else:
                print("无效选择，请重试")
        
    except KeyboardInterrupt:
        print("\n\n👋 用户退出")
    except Exception as e:
        print(f"❌ 错误: {e}")


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == "interactive":
        interactive_demo()
    else:
        main() 